package com.ideabove.util;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


public class ConnectThread extends Thread{
	int timeoutCount = 0;
	int tcount = 0;
	Callback callback = null;
	Object result = null;
	
	public interface Callback{		
		public void threadProcess(ConnectThread resultSet) throws Exception;
		public void sucess(Object result);
		public void fail(Object result);
	}
	
	public void setResult(Object result){
		this.result = result;
	}
	
	public ConnectThread(int timeout){
		this.timeoutCount = timeout;
	}
	
	public ConnectThread setCallback(Callback callback){
		this.callback = callback;
		return this;
	}
	
	@SuppressLint("HandlerLeak")
	Handler mMainHandler = new Handler() {

		public void handleMessage(Message msg) {
			if("sucess".equals(msg.obj)){
				if(callback != null){
					callback.sucess(result);
				}
			}else if("fail".equals(msg.obj)){
				if(callback != null){	
					callback.fail(result);
				}
			}
		}

	};
	
	public void sendMessage(String msg){
		mMainHandler.removeMessages(112);
		
		Message mssg = new Message();
		mssg.obj = msg;
		mssg.what = 112;
		mMainHandler.sendMessage(mssg);
	}
	
	
	@Override
	public void run(){
		try{
			this.setPriority(MAX_PRIORITY);
			if(this.callback != null){
				this.callback.threadProcess(this);
				sendMessage("sucess");
			}
		}catch(InterruptedException ie){
			ie.printStackTrace();
			return;
		}catch(Exception e){
			e.printStackTrace();
			tcount++;						
			
			if(this.tcount > this.timeoutCount){
				sendMessage("fail");				
			}else{
				try {
					Thread.sleep(100);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				run();
			}
		}
		
		
		
	}
}
